import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author YX
 * @date 2023/2/15 11:03
 */
public class ConsumerAndProducer {

    public static void main(String[] args) {
        AtomicLong index = new AtomicLong(0);
        List<Long> datas = new ArrayList<>();

        Thread product = new Thread(() -> {
            while (true) {

                synchronized (datas) {
                    if (datas.size() > 2000) {
                        try {
                            System.out.println("生产者-数据大于2000,我歇会" + datas.size());
                            datas.notify();
                            datas.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    datas.add(index.incrementAndGet());
                }
            }
        }, "producer");

        Thread consume = new Thread(() -> {
            while (true) {

                synchronized (datas) {
                    if (datas.size() < 100) {
                        try {
                            System.out.println("消费者-不能再消费了,已经低于100了" + datas.size());
                            datas.notify();
                            datas.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    datas.remove(0);
                }
            }
        }, "consumer");

        product.start();
        consume.start();
        System.out.println("任务已启动");
    }


}
